//
//  GiftListViewController.swift
//  LivelyChat
//
//  Created by admin on 2021/7/23.
//

import UIKit

class GiftListViewController: UIViewController {

    var backView:UIView!
    var collectView:UICollectionView!
    var numArr = ["9","39","69","99","199","399","999","1999"];
    var nameArr = ["Honey","Tea","Milk Tea","Seeds","Tea Hat","Tea Seedlings","Cheese","Cake"];

    var index = -1
    var giftImgView:UIImageView?
    var coninsLabel:UILabel!
    typealias giftSendBlock = (String) -> Void
    var block:giftSendBlock?
    var selString = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.backgroundColor = .blackComponent(0.3)
        self.navigationController?.navigationBar.isHidden = true
        
        let backTouchView = UIView(frame: self.view.bounds)
        backTouchView.isUserInteractionEnabled = true
        self.view.addSubview(backTouchView)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dimissAction))
        backTouchView.addGestureRecognizer(tap)

        self.backView = UIView(frame:CGRect(x: 0, y: screenHeight - 340.Fit, width: screenWidth, height: 340 + TabbarSafeBottomMargin))
        self.backView.backgroundColor = .color(hexString: "#062C01")
        self.backView.isUserInteractionEnabled = true
        self.view.addSubview(self.backView)
                
//        let addBtn = UIButton(frame: CGRect(x: KscreenWidth - 70, y: 18, width: 60, height: 20))
//        addBtn.backgroundColor = UIColor.init(hex: "#CD00FF")
//        addBtn.layer.masksToBounds = true
//        addBtn.layer.cornerRadius = 10
//        addBtn.layer.borderWidth = 1
//        addBtn.layer.borderColor = UIColor.init(hex: "#ECF906").cgColor
//        addBtn.setImage(UIImage(named: "+-1"), for: .normal)
//        addBtn.addTarget(self, action: #selector(rechargeAct), for: .touchUpInside)
//        self.backView.addSubview(addBtn)
        
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = CGSize(width:screenWidth/4,height:130)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

        self.collectView = UICollectionView(frame: CGRect(x: 0, y: 20, width: screenWidth, height: 275), collectionViewLayout: layout)
        self.collectView.backgroundColor = UIColor.color(hexString: "#3B3B4B")
        self.collectView.delegate = self
        self.collectView.dataSource = self
        self.collectView.backgroundColor = .clear
        self.collectView.register(Gift_Item.self, forCellWithReuseIdentifier: Gift_Item.description())
        self.backView.addSubview(self.collectView)
        self.collectView.reloadData()
        
        self.giftImgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
        self.giftImgView?.center = self.view.center;
        self.giftImgView?.contentMode = .scaleAspectFill
        self.view.addSubview(self.giftImgView!)
        self.giftImgView?.isHidden = true
        
        let sendBtn = UIButton(frame: CGRect(x: screenWidth - 105, y: 295, width: 75, height: 33))
        sendBtn.backgroundColor = mainColor
        sendBtn.layer.masksToBounds = true
        sendBtn.setTitle("Send", for: .normal)
        sendBtn.titleLabel?.font = .boldSystemFont(ofSize: 18)
        sendBtn.addTarget(self, action: #selector(sendGiftAct), for: .touchUpInside)
        sendBtn.setAllCorners(corner: 11)
        self.backView.addSubview(sendBtn)

        let rechargeImg = UIImageView(frame: CGRect(x: 15, y: 295, width: 40, height: 40))
        rechargeImg.image = UIImage(named: "coins1")
        self.backView.addSubview(rechargeImg)

        self.coninsLabel = UILabel(frame: CGRect(x: 65, y: 295, width: 100, height: 40))
        self.coninsLabel.font = .boldSystemFont(ofSize: 30)
        self.coninsLabel.textColor = .white
        self.coninsLabel.text = USEINFOMODEL.coins
        self.coninsLabel.textAlignment = .left
        self.backView.addSubview(self.coninsLabel)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refrshInfo), name: NSNotification.Name(rawValue: "coinsRefreshNotice"), object: nil)

    }
    
    @objc func refrshInfo() -> Void {
        if self.coninsLabel != nil {
            self.coninsLabel.text = USEINFOMODEL.coins ?? "0"
        }
    }

    @objc func rechargeAct() -> Void {
//        let vc = RechargeViewController()
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func returnBlock(block:@escaping giftSendBlock) -> Void {
        self.block = block
    }
    
    @objc func sendGiftAct() -> Void {
        if index == -1 {
            return
        }
        
        RT.buyGiftWith(cost: numArr[index]) {[self] (info) in
            self.giftImgView?.isHidden = false
            self.giftImgView?.image = UIImage(named:self.nameArr[self.index])
            self.backView.isHidden = true
            self.block?(nameArr[index])
            
            UIView.animate(withDuration: 1.5, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: {

                self.giftImgView?.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
                self.giftImgView?.center = self.view.center
                
            }) { (end) in
                if end
                {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        self.dismiss(animated: false, completion: nil)
                    }
                }
            }
        }
        
    }
    
    @objc func dimissAction(){
        self.dismiss(animated: false, completion: nil)
    }
    
}

extension GiftListViewController: UICollectionViewDelegate,UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selString = self.nameArr[indexPath.row]
        index = indexPath.row
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Gift_Item.description(), for: indexPath) as! Gift_Item
        cell.nameString = self.nameArr[indexPath.row]
        cell.coinsString = self.numArr[indexPath.row]
        cell.selectString = selString
        return cell
    }
    

}


class Gift_Item: UICollectionViewCell {
    
    let iconI = UIImageView.initImgView(img: "")
    let nameL = UILabel.initV(.setTypeFace(11.Fit,type: .medium), text: "", textColor: .white)
    let cL = UILabel.initV(.setTypeFace(11.Fit,type: .medium), text: "", textColor: .init(white: 1, alpha: 0.6))

    var nameString = ""{
        didSet{
            nameL.text = nameString
            self.iconI.image = .init(named: nameString)
        }
    }
    var coinsString = ""{
        didSet{
            cL.text = coinsString
        }
    }

    
    var selectString = ""{
        didSet{
            if nameString == selectString{
                contentView.layer.borderWidth = 2.Fit
                contentView.layer.borderColor = UIColor.white.cgColor
            }else
            {
                contentView.layer.borderWidth = 0
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.subviews {
            iconI
            nameL
            cL
        }
        contentView.setAllCorners(corner: 10.Fit)
        iconI.top(0).size(70.Fit)
        iconI.CenterX == contentView.CenterX
        nameL.left(0).right(0).height(20.Fit)
        nameL.Top == iconI.Bottom
        cL.left(0).right(0).height(15.Fit)
        cL.Top == nameL.Bottom + 5.Fit
        nameL.textAlignment = .center
        cL.textAlignment = .center
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
